#include"include/muduo/net/EventLoopThread.h"
#include"include/muduo/net/TcpClient.h"
#include"include/muduo/base/CountDownLatch.h"
#include"include/muduo/net/TcpConnection.h"
#include<string>
#include<iostream>
#include<functional>
class TranslateClient{

    public:
    TranslateClient(const std::string&sip,int sport):_client(_event.startLoop(),muduo::net::InetAddress(sip,sport),"TranslateClient"),_latch(1){
        _client.setConnectionCallback(std::bind(&TranslateClient::onConnection,this,std::placeholders::_1));
        _client.setMessageCallback(std::bind(&TranslateClient::onMassage,this,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3));
    }
    //建立连接----会阻塞等待
    void connect(){
        _client.connect();//这个连接会立即返回
        _latch.wait();//需要进行等待
    }

    bool send(const std::string&str){
        if(_conn->connected())
        {
            _conn->send(str);
            return true;
        }
        return false;
    }
    private:
    //连接服务器成功时调用函数---唤醒线程
    void onConnection(const muduo::net::TcpConnectionPtr&conn){
        if(conn->connected())
        {
            _latch.countDown();//唤醒线程
            _conn=conn;
        }
        else{
            _conn.reset();
        }
    }
    //收到消息时的回调函数
    void onMassage(const muduo::net::TcpConnectionPtr&conn,muduo::net::Buffer*buffer,muduo::Timestamp){
        std::cout<<"翻译结果: "<<buffer->retrieveAllAsString()<<std::endl;
    }

    private:
    muduo::net::EventLoopThread _event;
    muduo::net::TcpClient _client;
    muduo::net::TcpConnectionPtr _conn;
    muduo::CountDownLatch _latch;
    
};
int main()
{
    TranslateClient client("127.0.0.1",8888);
    client.connect();

    while(1)
    {
        std::cout<<"请输入:";
        std::string buffer;
        std::cin>>buffer;

        client.send(buffer);
    }
    return 0;
}